package com.larkmidtable.yunque.system;

import com.larkmidtable.yunque.YunQueEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.management.*;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 *
 *
 * @Date: 2023/6/15 23:30
 * @Description:
 **/
public class MachineInfo {
	private static Logger logger = LoggerFactory.getLogger(MachineInfo.class);
	private static NumberFormat fmtI = new DecimalFormat("###,###", new DecimalFormatSymbols(Locale.ENGLISH));

	/**
	 * 操作系统情况
	 * @return
	 */
	public static String getOSInfo(){
		OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
		StringBuffer osbuffer = new StringBuffer();
		osbuffer.append("操作系统的信息如下:"+"\r\n");
		osbuffer.append("操作系统名称：" + os.getName() +"\r\n");
		osbuffer.append("操作系统内核："+ os.getArch()+"\r\n");
		osbuffer.append("可用的处理器数量："+ os.getAvailableProcessors()+"\r\n");
		osbuffer.append("系统负载平均值："+ os.getSystemLoadAverage()+"\r\n");
		return osbuffer.toString();
	}

	/**
	 * JAVA版本信息
	 * @return
	 */
	public static String getJAVAInfo(){
		StringBuffer runbuffer = new StringBuffer();
		runbuffer.append("JAVA的版本：" + System.getProperty("java.version") +"\r\n");
		return runbuffer.toString();
	}

	public static void getJVMInfo() {
		List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
		for(MemoryPoolMXBean pool : pools) {
			final String kind = pool.getType().name();
			final MemoryUsage usage = pool.getUsage();
			logger.info("model:" + getKindName(kind)
					+ ", name:" + getPoolName(pool.getName())
					+ ", init:" + bytesToMB(usage.getInit())
					+ ", used:" + bytesToMB(usage.getUsed())
					+ ", available:" + bytesToMB(usage.getCommitted())
					+ ", max:" + bytesToMB(usage.getMax()));
		}
	}

	protected static String getKindName(String kind) {
		if("NON_HEAP".equals(kind)) {
			return "非堆内存";
		}else {
			return "堆内存";
		}
	}

	protected static String getPoolName(String poolName) {
		switch (poolName) {
			case "Code Cache":
				return "代码缓存区";
			case "Metaspace":
				return "元空间";
			case "Compressed Class Space":
				return "类指针压缩空间";
			case "PS Eden Space":
				return "伊甸园区";
			case "PS Survivor Space":
				return "幸存者区";
			case "PS Old Gen":
				return "老年代";
			default:
				return poolName;
		}
	}

	protected static String bytesToMB(long bytes) {
		return fmtI.format((long)(bytes / 1024 / 1024)) + " MB";
	}

	public static void main(String[] args) {
		MachineInfo.getJVMInfo();
	}
}
